package com.yuandian.management.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandian.api.management.entity.ConfOriginalDataFilter;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.security.util.SecurityUtils;
import com.yuandian.management.enums.ProbeFilterSyncEnum;
import com.yuandian.management.mapper.ConfOriginalDataFilterMapper;
import com.yuandian.management.service.ConfFilterBusinessDataService;
import com.yuandian.management.service.ConfOriginalDataFilterService;
import com.yuandian.management.utils.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 原始样包过滤配置表-Service实现
 * @author zfsn
 * @date 2023-4-12
 */
@Service
public class ConfOriginalDataFilterServiceImpl extends ServiceImpl<ConfOriginalDataFilterMapper, ConfOriginalDataFilter>
		implements ConfOriginalDataFilterService {
	@Autowired
	ConfOriginalDataFilterMapper confOriginalDataFilterMapper;

	@Autowired
	ConfFilterBusinessDataService businessDataService;

	/**
	 * 分页查询
	 *
	 * @param confOriginalDataFilter 筛选条件
	 * @return 通用返回对象
	 */
	@Override
	public Page<ConfOriginalDataFilter> listPage(ConfOriginalDataFilter confOriginalDataFilter) {
		Page<ConfOriginalDataFilter> dataFilterPage = confOriginalDataFilterMapper.listPage(new Page<>(confOriginalDataFilter.getPageNum(), confOriginalDataFilter.getPageSize()), confOriginalDataFilter);
		if (CollectionUtils.isNotEmpty(dataFilterPage.getRecords())) {
			// 查询当前已经捕获的条数且更新当前的数据
			List<Integer> filterIds = dataFilterPage.getRecords().stream().map(ConfOriginalDataFilter::getId).collect(Collectors.toList());
			Map<Integer, Integer> map = businessDataService.countByFilterIds(filterIds);
			for (ConfOriginalDataFilter originalDataFilter : dataFilterPage.getRecords()) {
				Integer captureCount = map.get(originalDataFilter.getId());
				originalDataFilter.setCaptureCount(captureCount);
			}
		}
		return dataFilterPage;
	}

	/**
	 * 新增数据
	 *
	 * @param confOriginalDataFilter 实例对象
	 * @return 通用返回对象
	 */
	@Override
	public R<String> saveConfig(ConfOriginalDataFilter confOriginalDataFilter) {
		confOriginalDataFilter.setIsEnable(confOriginalDataFilter.getStatus());
		 super.save(convertOriginalDataFilterToVo(confOriginalDataFilter));
		 return R.ok();
	}


	/**
	 * 对象转换
	 *
	 * @param confOriginalDataFilter 参数
	 * @return OriginalDataFilterVo
	 */
	private ConfOriginalDataFilter convertOriginalDataFilterToVo(ConfOriginalDataFilter confOriginalDataFilter) {
		String username = SecurityUtils.getUser().getName();
		if (!StringUtils.isEmpty(confOriginalDataFilter.getKeyword())) {
			String skeyword = JacksonUtil.objectToString(confOriginalDataFilter.getKeyword()).substring(1, JacksonUtil.objectToString(confOriginalDataFilter.getKeyword()).length() - 1);
			String keyw = skeyword.replace(":", "\\:");
			String keyword = keyw.replace(",", "\\,");
			confOriginalDataFilter.setKeyword(keyword);
		}
		if (!StringUtils.isEmpty(confOriginalDataFilter.getRequestIp())) {
			confOriginalDataFilter.setRequestIp(confOriginalDataFilter.getRequestIp().replace(",", "\\,"));
		}
		if (!StringUtils.isEmpty(confOriginalDataFilter.getResponseIp())) {
			confOriginalDataFilter.setResponseIp(confOriginalDataFilter.getResponseIp().replace(",", "\\,"));
		}
		if (StringUtils.isEmpty(confOriginalDataFilter.getStartTime())) {
			confOriginalDataFilter.setStartTime(null);
		}
		if (StringUtils.isEmpty(confOriginalDataFilter.getEndTime())) {
			confOriginalDataFilter.setEndTime(null);
		}
		if (!StringUtils.isEmpty(confOriginalDataFilter.getId())) {
			confOriginalDataFilter.setId(confOriginalDataFilter.getId());
		}
		if (!StringUtils.isEmpty(confOriginalDataFilter.getCaptureCount())) {
			confOriginalDataFilter.setCaptureCount(confOriginalDataFilter.getCaptureCount());
		}
		if (!StringUtils.isEmpty(confOriginalDataFilter.getCapturedCount())) {
			confOriginalDataFilter.setCapturedCount(confOriginalDataFilter.getCapturedCount());
		} else {
			confOriginalDataFilter.setCapturedCount(0);
		}
		if (StringUtils.isEmpty(confOriginalDataFilter.getId())) {
			confOriginalDataFilter.setEnable(0);
			confOriginalDataFilter.setStatus(0);
		}
		confOriginalDataFilter.setCreateBy(username);
		confOriginalDataFilter.setCreateTime(LocalDateTime.now());
		return confOriginalDataFilter;
	}


	/**
	 * 通过主键更新数据
	 *
	 * @param confOriginalDataFilter 实例对象
	 * @return 通用返回对象
	 */
	@Override
	public R updateConfigById(ConfOriginalDataFilter confOriginalDataFilter) {
		//在这判断是否能进行编辑操作
		ConfOriginalDataFilter dataFilter = super.getById(confOriginalDataFilter.getId());
		Integer executeStatus = dataFilter.getEnable();
		Integer isStatus = dataFilter.getIsEnable();
		Integer syncStatus = dataFilter.getStatus();
		//  未执行 +正在同步
		if (ProbeFilterSyncEnum.NOW_SYNC.getType().equals(syncStatus)
				&& ProbeFilterSyncEnum.NOT_EXECUTE.getType().equals(executeStatus)) {
			return R.failed("该规则正在同步不能进行编辑！");
		}
		// 启用 + 同步完成+ 执行中
		if (ProbeFilterSyncEnum.IN_EXECUTE.getType().equals(executeStatus)
				&& ProbeFilterSyncEnum.START.getType().equals(isStatus)
				&& ProbeFilterSyncEnum.OK_SYNC.getType().equals(syncStatus)) {
			return R.failed("该规则正在执行,不能编辑！");
		}
		// 编辑需要实时流做出相应的操作
		confOriginalDataFilter.setIsDel(ProbeFilterSyncEnum.DEL_FILTER.getType());
		super.updateById(convertOriginalDataFilterToVo(confOriginalDataFilter));
		ConfOriginalDataFilter odf = new ConfOriginalDataFilter();
		odf.setId(confOriginalDataFilter.getId());
		odf.setStatus(ProbeFilterSyncEnum.NOW_SYNC.getType());
		super.updateById(odf);
		odf.setEnable(ProbeFilterSyncEnum.NOT_EXECUTE.getType());
		super.updateById(odf);
		return R.ok();
	}

	/**
	 * 修改原始包捕获规则  禁用启用
	 *
	 * @param confOriginalDataFilter 参数
	 * @return Result
	 */
	@Override
	public R updateStatusByIds(ConfOriginalDataFilter confOriginalDataFilter) {
		List<Integer> ids = confOriginalDataFilter.getIds();
		if(ObjectUtil.isEmpty(ids)){
			ids = new ArrayList<>();
			Integer id = confOriginalDataFilter.getId();
			if(id == null){
				return R.failed("修改失败，请检查请求参数！");
			}
			ids.add(id);
		}
		//在这判断是否能进行编辑操作
		List<ConfOriginalDataFilter> confOriginalDataFilters = super.listByIds(ids);
		for (ConfOriginalDataFilter dataFilter : confOriginalDataFilters) {
			Integer executeStatus = dataFilter.getEnable();
			Integer isStatus = dataFilter.getIsEnable();
			Integer syncStatus = dataFilter.getStatus();
			//  未执行 +正在同步
			if (ProbeFilterSyncEnum.NOW_SYNC.getType().equals(syncStatus)
					&& ProbeFilterSyncEnum.NOT_EXECUTE.getType().equals(executeStatus)) {
				return R.failed("该规则正在同步不能进行编辑！");
			}
			// 启用 + 同步完成+ 执行中
			if (ProbeFilterSyncEnum.IN_EXECUTE.getType().equals(executeStatus)
					&& ProbeFilterSyncEnum.START.getType().equals(isStatus)
					&& ProbeFilterSyncEnum.OK_SYNC.getType().equals(syncStatus)) {
				return R.failed("该规则正在执行,不能编辑！");
			}
		}
		Integer dr = ProbeFilterSyncEnum.STOP.getType().equals(confOriginalDataFilter.getEnable()) ?
				ProbeFilterSyncEnum.DEL_LOCAL_RULE.getType() : ProbeFilterSyncEnum.ADD_LOCAL_RULE.getType();
		confOriginalDataFilterMapper.startOrStopStatus(ids, confOriginalDataFilter.getIsEnable(), dr);
		return R.ok();
	}

	/**
	 * 通过主键删除数据
	 *
	 * @param ids 主键
	 * @return 通用返回对象
	 */
	@Override
	public R deleteByIds(List<Integer> ids) {
		List<ConfOriginalDataFilter> filterEos = super.listByIds(ids);
		//判断哪些可以删除(同步成功且 (执行完成或者未执行))
		for (ConfOriginalDataFilter filterEo : filterEos) {
			Integer syncStatus = filterEo.getStatus();
			Integer executeStatus = filterEo.getEnable();
			LocalDateTime syncTime = filterEo.getSyncTime();
			if (null != syncTime) {
				if (ProbeFilterSyncEnum.OK_SYNC.getType().equals(syncStatus) &&
						!ProbeFilterSyncEnum.IN_EXECUTE.getType().equals(executeStatus)) {
				} else {
					return R.failed("该规则当前不能被删除");
				}
			}
		}
		// 批量更新该配置为 dr = 1 和状态
		confOriginalDataFilterMapper.logicDelByIds(ids, ProbeFilterSyncEnum.NOW_SYNC.getType());
		/*        删除成功,捕获数据将在同步成功后删除*/
		return R.ok();
	}

	/**
	 * 保存原始包捕获规则
	 *
	 * @param confOriginalDataFilter 参数
	 * @return Result
	 */
	@Override
	public R syncFilterRule(ConfOriginalDataFilter confOriginalDataFilter) {
		// 查询原本的数据,下面需要判断是否是新建
		List<ConfOriginalDataFilter> filterEos = confOriginalDataFilterMapper.listByIds(confOriginalDataFilter.getIds());
		for (ConfOriginalDataFilter filterEo : filterEos) {
			// 新建/编辑同步规则只能是启用状态才行
			Integer startOrStopStatus = filterEo.getIsEnable();
			Integer syncStatus = filterEo.getStatus();
			Integer executeStatus = filterEo.getEnable();
			if (ProbeFilterSyncEnum.IN_EXECUTE.getType().equals(executeStatus)
					|| ProbeFilterSyncEnum.OK_EXECUTE.getType().equals(executeStatus)
					|| ProbeFilterSyncEnum.NOW_SYNC.getType().equals(syncStatus)
					|| ProbeFilterSyncEnum.STOP.getType().equals(startOrStopStatus)) {
				return R.failed("该规则状态不能同步");
			}
			Integer dr = ProbeFilterSyncEnum.ADD_LOCAL_RULE.getType();
			// 修改状态为重新同步，
			confOriginalDataFilterMapper.updateFilterStatusByIds(confOriginalDataFilter.getIds(), ProbeFilterSyncEnum.NOW_SYNC.getType(), null, dr);
		}
		return R.ok();
	}

	/**
	 * 查询原始包捕获规则数据
	 *
	 * @return Result
	 */
	@Override
	public List<Map<String, Object>> findName() {
		return confOriginalDataFilterMapper.queryRuleNameMap();
	}


}
